#ifdef NON_OS

#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/ioctl.h>
#endif

#include <config.h>

#ifdef GPU_SUPPORT

#include <types.h>
#include <drivers/graphic/gpu.h>
#include <drivers/graphic/glt.h>

extern int fb;

/* The GLT index is staring from 0, so we initialize it to -1 */
s8 glt_layer_idx_counter = GLT_START_INDEX;
s8 glt_layer_idx_start = GLT_START_INDEX;

#ifndef NON_OS
pthread_mutex_t glt_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif

inline void glt_reset_index(void)
{
    glt_layer_idx_counter = glt_layer_idx_start;
}

inline s8 glt_get_current_index(void)
{
    return glt_layer_idx_counter;
}

inline void glt_index_inc(void)
{
    ++glt_layer_idx_counter;
}

u32 glt_read(int index, GLT *glt)
{
    int idx = index;
    ioctl(fb, FBIOCTL_SET_GLTIDX, &idx);
    ioctl(fb, FBIOCTL_GET_GLT, glt);
    return 0;
}

u32 glt_write(int index, GLT *glt)
{
    int idx = index;
    ioctl(fb, FBIOCTL_SET_GLTIDX, &idx);
    ioctl(fb, FBIOCTL_SET_GLT, glt);
    return 0;
}

inline void glt_start_index_reset(s8 reset)
{
    glt_layer_idx_start = reset;
}

inline void glt_lock()
{
#ifndef NON_OS
    pthread_mutex_lock(&glt_mutex);
#endif
}

inline void glt_unlock()
{
#ifndef NON_OS
    pthread_mutex_unlock(&glt_mutex);
#endif
}

#endif /* GPU_SUPPORT */
